package com.lagou.work.service;

import com.lagou.work.*;
import com.lagou.work.handler.UserServerHandler;
import com.lagou.work.zookeeper.registry.RpcRegistryHandler;
import com.lagou.work.zookeeper.registry.impl.RpcRegistryHandlerImpl;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    public String sayHallow(String message) {
        System.out.println("接收信息：" + message);
        return "success";
    }

    public static void startServer(String address, Integer port) throws InterruptedException {
        // 1.创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        // 2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        // 3.配置启动引导对象
        serverBootstrap.group(bossGroup, workGroup)
                // 设置通道为NIO
                .channel(NioServerSocketChannel.class)
                // 创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        // 获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        // 给管道对象pipLine 设置编码
                        pipeline.addLast(new StringEncoder());
//                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));

                        // 把我们自定义的一个ChannelHandler添加到通道中
                        pipeline.addLast(new UserServerHandler());
                    }
                });

        // 4.绑定端口
        ChannelFuture sync = serverBootstrap.bind(address, port).sync();
        System.out.println("服务端已启动");
        if (sync.isSuccess()) {
            RpcRegistryHandler rpcRegistryHandler = new RpcRegistryHandlerImpl();
            rpcRegistryHandler.registry(UserService.class.getName(), address, port);
            System.out.println("服务端已注册");
        }
    }


}
